<template>
  <div>
    <!-- 1.顶部栏 -->
    <van-nav-bar title="搜索页" left-arrow @click-left="$router.back()" />
    <!-- 2.搜索框 -->
    <van-search
      v-model="value"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <!-- 3.搜索列表 -->
    <van-cell-group>
      <van-cell
        v-for="(item, index) in showList"
        :key="index"
        icon="search"
      >
        <template #title>
          <span class="custom-title" v-html="item"></span>
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
//导入接口
import { getSuggestion } from './home.js'
export default {
  name: 'search',
  data () {
    return {
      value: '', //搜索内容
      suggestionList: [] //推荐词列表
    }
  },
  methods: {
    /* 搜索事件： 输入框回车 + 点击右侧搜索按钮 */
    onSearch () {
      console.log('搜索' + this.value)
    },
    /* 输入事件：输入框内容变化 */
    async onInput () {
      console.log('输入' + this.value)
      //0.非空判断
      if (this.value == '') {
        this.suggestionList = []
        return
      }
      //1.获取推荐词列表
      let res = await getSuggestion(this.value)
      console.log(res)
      //2.绑定数据
      this.suggestionList = res.data.data.options
    }
  },
  computed: {
    showList () {
      //map:遍历数组，根据某种映射规则生成一个新数组
      return this.suggestionList.map(value => {
        let reg = new RegExp(this.value, 'ig')
        return value.replace(
          reg,
          match => `<span style="color:red">${match}</span>`
        )
      })
    }
  }
}
</script>

<style></style>
